package com.pdg.mcplugin.tfbal;

import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;

import com.pdg.mcplugin.common.PlayerUtilities;
import com.pdg.mcplugin.common.baseclasses.PluginClientBase;

public class TFBALEventListener extends PluginClientBase<TFBAL> implements Listener{

	public TFBALEventListener(TFBAL thePlugin) {
		super(thePlugin);
	}

	@EventHandler
	public void onPlayerInteract(PlayerInteractEvent theEvent){
		Player thePlayer = theEvent.getPlayer();
		if(getPlugin().getPermissionChecker().checkAvoidPermission(thePlayer)){
			return;
		}
		Block theBlock = theEvent.getClickedBlock();
		Action theAction = theEvent.getAction();
		if(theAction== Action.RIGHT_CLICK_BLOCK){
			if(theBlock!=null){
				Material theBlockMaterial = theBlock.getType();
				switch(theBlockMaterial){
				case STONE_BUTTON:
					handleStoneButtonInteraction(thePlayer,theEvent);
					break;
				case LEVER:
					handleLeverInteraction(thePlayer,theEvent);
					break;
				default:
					return;
				}
			}
		}
	}

	private void handleLeverInteraction(Player thePlayer,
			PlayerInteractEvent theEvent) {
		if(chargePayment(thePlayer)){
			sendSuccessMessage(thePlayer,TFBALMessages.LEVER_SUCCESS);
		}else{
			sendFailureMessage(thePlayer,TFBALMessages.LEVER_FAILURE);
			theEvent.setCancelled(true);
		}
	}

	private void handleStoneButtonInteraction(Player thePlayer,
			PlayerInteractEvent theEvent) {
		if(chargePayment(thePlayer)){
			sendSuccessMessage(thePlayer,TFBALMessages.BUTTON_SUCCESS);
		}else{
			sendFailureMessage(thePlayer,TFBALMessages.BUTTON_FAILURE);
			theEvent.setCancelled(true);
		}
	}

	private void sendFailureMessage(Player thePlayer, TFBALMessages theMessage) {
		if(getPlugin().getConfigurationManager().isMessageEnabled(theMessage)){
			getPlugin().sendErrorMessage(thePlayer, getPlugin().getConfigurationManager().getMessageText(theMessage));
		}
	}

	private void sendSuccessMessage(Player thePlayer, TFBALMessages theMessage) {
		if(getPlugin().getConfigurationManager().isMessageEnabled(theMessage)){
			getPlugin().sendSuccessMessage(thePlayer, getPlugin().getConfigurationManager().getMessageText(theMessage));
		}
	}

	private boolean chargePayment(Player thePlayer) {
		ItemStack theCost = getPlugin().getConfigurationManager().getCost();
		int theCount = PlayerUtilities.getPlayerItemCount(thePlayer, theCost.getData());
		if(theCount>=theCost.getAmount()){
			PlayerUtilities.removePlayerItemCount(thePlayer, theCost.getData(), theCost.getAmount());
			return true;
		}else{
			return false;
		}
	}
}
